package com.mashibing.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMQ连接工具类
 */
public class RabbitMQConnectionUtil {
    // RabbitMQ服务器的主机地址
    public static final String RABBITMQ_HOST = "192.168.86.138";
    // RabbitMQ服务器的端口号
    public static final int RABBITMQ_PORT = 5672;
    // RabbitMQ服务器的用户名
    public static final String RABBITMQ_USERNAME = "guest";
    // RabbitMQ服务器的密码
    public static final String RABBITMQ_PASSWORD = "guest";
    // RabbitMQ服务器的虚拟主机
    public static final String RABBITMQ_VIRTUAL_HOST = "/";

    /**
     * 获取与RabbitMQ服务器的连接
     *
     * @return Connection对象，用于与RabbitMQ服务器通信
     * @throws IOException 如果创建连接时发生I/O错误
     * @throws TimeoutException 如果创建连接时发生超时
     */
    public static Connection getConnection() throws IOException, TimeoutException {
        // 1.创建Connection工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置RabbitMQ的连接信息
        factory.setHost(RABBITMQ_HOST);
        factory.setPort(RABBITMQ_PORT);
        factory.setUsername(RABBITMQ_USERNAME);
        factory.setPassword(RABBITMQ_PASSWORD);
        factory.setVirtualHost(RABBITMQ_VIRTUAL_HOST);
        // 3.返回连接对象
        Connection connection = factory.newConnection();
        return connection;
    }
}

